package com.atguigu.day02.transform;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import sun.awt.SunHints;

/**
 * 当需要连接MySQL或者Redis时，普通Map会在来一个元素时就连接一次MySQL，导致效率低
 * Map_Rich :Rich方法会提供open和close两中方法，使得一个并行度只需要创建一次连接即可
 */
public class Flink02_Map_Rich {
    public static void main(String[] args) {
         Configuration conf = new Configuration();
          //配置web页面固定端口
          conf.setInteger("rest.port", 20000);
          //创建流环境
          StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
          //设置并行度
          env.setParallelism(2);

        DataStreamSource<Integer> stream = env.fromElements(1, 2, 3, 5, 7, 8, 9);

        stream.map(new RichMapFunction<Integer, Integer>() {
            @Override
            public void open(Configuration parameters) throws Exception {
                //与外部存储建立连接，且建立连接次数=并行度
                System.out.println("open ...");
            }

            @Override
            public Integer map(Integer value) throws Exception {
                return value * value;
            }

            @Override
            public void close() throws Exception {
                //关闭连接
                System.out.println("close ...");
            }
        }).print();

        try {
              env.execute();
          } catch (Exception e) {
              e.printStackTrace();
          }
    }
}
